package io.renren.modules.job.task;

import io.renren.modules.sale.entity.SaleOrderEntity;
import io.renren.modules.sale.service.SaleOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/*
 * @author Cliff.ZhouYang
 * @date 2018/3/19 18:03
 */
@Component("orderTask")
@Slf4j
public class OrderTask {
    @Autowired
    private SaleOrderService saleOrderService;

    @Scheduled(initialDelay = 1000, fixedDelay = 60000000)
    public void execute() throws Exception {
        log.info("网络爬虫准备开始，即将进行登录。。。");
        CookieStore cs = new BasicCookieStore();

        DefaultHttpClient httpclient = new DefaultHttpClient();

        // 创建一个本地上下文信息
        HttpContext localContext = new BasicHttpContext();
        // 在本地上下问中绑定一个本地存储
        localContext.setAttribute(ClientContext.COOKIE_STORE, cs);

        // 目标地址
        HttpPost httppost = new HttpPost("https://www.itou.com/user/login/do");

        System.out.println("请求: " + httppost.getRequestLine());
        // 构造最简单的字符串数据
        StringEntity reqEntity = new StringEntity("user_name=invinci123&password=19890405a");
        // 设置类型
        reqEntity.setContentType("application/x-www-form-urlencoded");
        // 设置请求的数据
        httppost.setEntity(reqEntity);
        // 执行
        HttpResponse response = httpclient.execute(httppost);

        Header[] headers = response.getAllHeaders();
        for (Header h : headers) {
            String name = h.getName();
            String value = h.getValue();
            System.out.println("header : " + h.getName() + ":" + h.getValue());

            if ("Set-Cookie".equalsIgnoreCase(name)) {
                String[] strs = value.split(";");
                for (String str : strs) {
                    String[] cookies = str.split("=");
                    System.out.println("=============== : " + cookies[0] + ":" + cookies[1]);
                    cs.addCookie(new BasicClientCookie(cookies[0], cookies[1]));
                }
            }

        }

        HttpEntity entity = response.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        // 显示结果
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String line = null;
        while ((line = reader.readLine()) != null) {
//            System.out.println(line);
        }

        for (int i = 0; i < 4; i++) {
            opera(cs, i + 1);
        }
    }

    private void opera(CookieStore cs, int page) throws Exception {
        System.out.println("----------------------------------------");

        String logPath = "https://www.itou.com/station/admin/project/ticketing/?stime=2018-03-16&etime=2018-03-19&timeType=consignTime&submitType=1";
        logPath = "https://www.itou.com/station/admin/project/ticketing/?stime=2018-03-15&etime=2018-04-01&timeType=consignTime&orderStatus=1&page=" + page;

        DefaultHttpClient httpclient = new DefaultHttpClient();

        String cookieStr = "";
        List<Cookie> list = cs.getCookies();
        for (Cookie cookie : list) {
            cookieStr += cookie.getName() + "=" + cookie.getValue() + ";";
        }

        // 目标地址
        HttpGet httpget = new HttpGet(logPath);
        httpget.setHeader("Cookie", cookieStr);

        System.out.println("请求: " + httpget.getRequestLine());
        // 设置类型
        // 执行
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                entity.getContent(), "UTF-8"));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }


        Document document = Jsoup.parse(sb.toString());
//            Elements elements = document.getElementsByClass("admintable");

        Elements elements = document.getElementsByTag("tbody");
        Elements e = elements.tagName("tr").get(0).children();
        Iterator<Element> iterator = e.iterator();
        while (iterator.hasNext()) {
            Element tr = iterator.next();

            Element td0 = tr.getElementsByTag("td").get(0);//<td order_status="1" tally_id="133127215" type_name="竞足比分" lottery_style="jc" lottery_no="2018-03-28" launch_money="24" auto_merge_ticket="1" cash_type="1" end_time="1522252800" mobile="" remark_name="赵林鹏" payment_en="payment_weixin" payment_cn="微信" payment_account="gent_zhao" partner="itou" period_num="1" start_no="">
            String tallyId = td0.attr("tally_id");
            String orderStatus = td0.attr("order_status");
            String lotteryStyle = td0.attr("lottery_style");
            String launchMoney = td0.attr("launch_money");
            String typeName = td0.attr("type_name");
            String remarkName = td0.attr("remark_name");
            String cashType = td0.attr("cash_type");

            Element td2 = tr.getElementsByTag("td").get(2);//<td><div class="paidantd"><a href="javascript:void(0);" id="projecturl_134257695" class="projecturl" uid="50264189" tally_id="134257695">16885729</a>
            String orderId = td2.getElementsByTag("a").html();

            Element td3 = tr.getElementsByTag("td").get(3);//<td><div class="usernamecard" style="z-index: 1;"><a showusercard="50264189" tally_id="134257695" href="javascript:void(0);">NovemberRain</a></div></td>
            String customId = tr.getElementsByTag("a").attr("showusercard");

            SaleOrderEntity saleOrder = new SaleOrderEntity();
            saleOrder.setLaunchMoney(Double.valueOf(launchMoney));
            saleOrder.setTallyId(tallyId);// 主键ID
            saleOrder.setOrderId(orderId);// 方案编号
            saleOrder.setOrderStatus(Integer.valueOf(orderStatus));// 出票状态 1出票成功 2出票失败 3合买方案 4等待处理 5过点撤销 6未接单 7等待结账
            saleOrder.setCashType(Integer.valueOf(cashType));// 支付方式 1现金 2余额 3扫码付
            saleOrder.setRemarkName(remarkName);
            saleOrder.setLotteryStyle(lotteryStyle);//玩法大类
            saleOrder.setTypeName(typeName);// 玩法小类
            saleOrder.setCustomId(customId);// 用户ID
            saleOrder.setCreateTime(new Date());

            SaleOrderEntity temp = saleOrderService.selectById(tallyId);
            if (temp == null) {
                saleOrderService.insert(saleOrder);
            } else {
                saleOrderService.updateById(saleOrder);
            }
        }

    }
}
